package cloud.admin.gateway.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cloud.admin.gateway.dao.RouteMapper;
import cloud.admin.gateway.dto.GatewayRouteDefinition;
import cloud.admin.gateway.entity.GatewayRoutes;
import cloud.admin.gateway.service.IRoutesService;
@Service
public class RoutesServiceImpl implements IRoutesService{

	@Autowired
	private RouteMapper routeMapper;
	
	@Override
	public int add(GatewayRoutes gatewayRoute) {
		gatewayRoute.setCreateTime(new Date());
		gatewayRoute.setUpdateTime(new Date());
		gatewayRoute.setIsDel(false);
		gatewayRoute.setIsEbl(false);
		return routeMapper.insertRoute(gatewayRoute);
	}

	@Override
	public int update(GatewayRoutes gatewayRoute) {
		gatewayRoute.setUpdateTime(new Date());
		return routeMapper.updateByPrimaryKeySelective(gatewayRoute);
	}

	@Override
	public int delete(Long id, boolean isDel) {
		return routeMapper.deleteByPrimaryKey(id , isDel);
	}

	@Override
	public int enableById(Long id, boolean isEbl) {
		return routeMapper.enableById(id , isEbl);
	}

	@Override
	public GatewayRoutes getRouteById(Long id) {
		return routeMapper.selectByPrimaryKey(id);
	}

	/**
	 * 查询路由信息
	 */
	@Override
	public List<GatewayRoutes> getRoutes(GatewayRoutes route) {
		return routeMapper.getRoutes(route);
	}

	/**
	 * 返回组装成网关需要的路由信息
	 */
	@Override
	public List<GatewayRouteDefinition> getRouteDefinitions() {
		List<GatewayRouteDefinition> routeDefinitions = new ArrayList<GatewayRouteDefinition>();
		GatewayRoutes route = new GatewayRoutes();
		route.setIsDel(false);
		route.setIsEbl(false);
		List<GatewayRoutes> routes = getRoutes(route);
		for (GatewayRoutes gatewayRoutes : routes) {
            GatewayRouteDefinition routeDefinition = new GatewayRouteDefinition();
            routeDefinition.setId(gatewayRoutes.getRouteId());
            routeDefinition.setUri(gatewayRoutes.getRouteUri());
            routeDefinition.setFilters(gatewayRoutes.getFilterDefinition());
            routeDefinition.setPredicates(gatewayRoutes.getPredicateDefinition());
            routeDefinitions.add(routeDefinition);
		}
		
		return routeDefinitions;
	}

}
